package com.example.a11

import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Bundle
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import kotlin.concurrent.thread

class SongFragment : Fragment(), ServiceConnection {
    private var binder: MusicService.MusicBinder? = null
    private lateinit var seekBar: SeekBar
    private lateinit var songName: TextView
    private lateinit var songCount: TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.newtest_1, container, false)

        seekBar = view.findViewById(R.id.seekBar)
        songName = view.findViewById(R.id.songName)
        songCount = view.findViewById(R.id.songCount)

        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.READ_MEDIA_AUDIO), 0)
        } else {
            startMusicService()
        }

        setupSeekBar(view)

        view.findViewById<Button>(R.id.playsongs).setOnClickListener { onPlay() }
        view.findViewById<Button>(R.id.pausesongs).setOnClickListener { onPauseSong() }
        view.findViewById<Button>(R.id.stopsongs).setOnClickListener { onStopSong() }
        view.findViewById<Button>(R.id.nextsongs).setOnClickListener { onNext() }
        view.findViewById<Button>(R.id.prevsongs).setOnClickListener { onPrev() }

        return view
    }

    private fun setupSeekBar(view: View) {
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
    }

    private fun startMusicService() {
        val intent = Intent(requireContext(), MusicService::class.java)
        requireContext().startService(intent)
        requireContext().bindService(intent, this, Context.BIND_AUTO_CREATE)
    }

    private fun onPlay() {
        binder?.play()
    }

    private fun onPauseSong() {
        binder?.pause()
    }

    private fun onStopSong() {
        binder?.stop()
    }

    private fun onNext() {
        binder?.next()
    }

    private fun onPrev() {
        binder?.prev()
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder = service as MusicService.MusicBinder
        thread {
            while (binder != null) {
                Thread.sleep(1000)
                requireActivity().runOnUiThread {
                    seekBar.max = binder!!.duration
                    seekBar.progress = binder!!.currentPosition
                    songName.text = binder!!.musicName
                    songCount.text = "${binder!!.currentIndex + 1}/${binder!!.size}"
                }
            }
        }
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        binder = null
    }

    override fun onDestroy() {
        super.onDestroy()
        if (binder != null) {
            requireContext().unbindService(this)
        }
    }

    companion object {
        fun newInstance() = SongFragment()
    }
}